package com.example.servicefeign.interceptor;

import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.Callable;


/**
 * 由于hystrix是通过线程池来发送请求的，所以trace_id未透传到服务提供方
 *
 */
@Component
public class MdcHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(contextMap);
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    /**
     * 注册hystrix的mdc strategy，传递trace_id
     */
    @PostConstruct
    public void hystrixInit() {
        HystrixPlugins.getInstance().registerConcurrencyStrategy(new MdcHystrixConcurrencyStrategy());
    }
}